<template>
    <el-upload accept="image/jpeg, image/png, image/gif, image/webp, image/svg" class="avatar-uploader" :action="action" :show-file-list="false" :on-success="handleUploadSuccess">
        <img v-if="img_url" :src="img_url" class="avatar" style="width:100%;height:100%;"/>
        <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
        </el-icon>
    </el-upload>
</template>
<script setup>

import { Plus } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'

const props = defineProps({
    src: { type: String }
})

const emits = defineEmits(['upload-change'])

const img_url = defineModel({
    value: { type: String, default: '' }
})

const action = `${import.meta.env.VITE_UPLOAD_IMAGE_URL}`

/**
 * 上次成功操作后的回调
 * @param response
 * @param uploadFile
 */
function handleUploadSuccess (response, uploadFile) {
    img_url.value = response.data.url
}

/**
 * 上传文件前的操作
 * @param rawFile
 * @returns {boolean}
 */
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    width: 100px;
    height: 100px;
    img {
        width: auto;
        height: 100%;
    }
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
}
</style>